package com.jcodecraeer.xrecyclerview;

import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.app.Context;

public class SimpleViewSwitcher extends ComponentContainer {
    public SimpleViewSwitcher(Context context) {
        super(context);
        init();
    }

    public SimpleViewSwitcher(Context context, AttrSet attrSet) {
        super(context, attrSet);
        init();
    }

    public SimpleViewSwitcher(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
        init();
    }

    private void init(){

        setEstimateSizeListener(new EstimateSizeListener() {
            @Override
            public boolean onEstimateSize(int widthEstimateConfig, int heightEstimateConfig) {
                int childCount = SimpleViewSwitcher.this.getChildCount();
                int maxHeight = 0 ;
                int maxWidth = 0;
                for(int i = 0; i < childCount ;i++){
                    Component child = SimpleViewSwitcher.this.getComponentAt(i);
                    maxWidth  = child.getEstimatedWidth();
                    maxHeight = child.getEstimatedHeight();
                }
                setEstimatedSize(maxWidth,maxHeight);
                return true;
            }
        });
        setLayoutRefreshedListener(new LayoutRefreshedListener() {
            @Override
            public void onRefreshed(Component component) {
                final int count = getChildCount();
                for (int i = 0; i < count; i++) {
                    final Component child = getComponentAt(i);
                    if (child.getVisibility() != HIDE) {
                        child.arrange(0,0,getWidth() - getLeft(),getHeight() - getTop());
                    }
                }
            }
        });
    }

    public void setView(Component componet){
        if(this.getChildCount() != 0){
            this.removeComponentAt(0);
        }
        this.addComponent(componet,0);
    }
}
